package com.site.service.impl;

import com.site.dao.ReceiveDetailDao;
import com.site.dao.ReserveDao;
import com.site.dao.impl.ReceiveDetailDaoImpl;
import com.site.dao.impl.ReserveDaoImpl;
import com.site.pojo.ReceiveDetail;
import com.site.pojo.Reserve;
import com.site.service.ReceiveDetailService;
import com.site.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

public class ReceiveDetailServiceImpl implements ReceiveDetailService {
    private ReceiveDetailDao receiveDetailDao = new ReceiveDetailDaoImpl();
    private ReserveDao reserveDao = new ReserveDaoImpl();
    /**
     * 入库明细表
     *
     * @param list
     * @return
     */
    @Override
    public boolean addReceiveDetail(List<ReceiveDetail> list) {
        Connection conn = null;
        ReceiveDetail receiveDetail = new ReceiveDetail();
        boolean flag = false;
        try{
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            Iterator<ReceiveDetail> it = list.iterator();
            while (it.hasNext()){
                receiveDetail = it.next();
                int num1 = receiveDetailDao.addReceiveDetail(conn,receiveDetail);
                //获取数量
                Long receiveCount = receiveDetail.getReceiveCount();
                int counts =Integer.parseInt(receiveCount.toString());
                //获取货架编号
                Long rid = receiveDetail.getRtid();
                Reserve reserve = reserveDao.selectByid(Integer.parseInt(rid.toString()));
                reserve.setQuantity(reserve.getAmount()+counts);
                reserve.setGoodsId(receiveDetail.getGoodsId());
                reserve.setNeednum(reserve.getAmount()-reserve.getQuantity());
                if(reserve.getQuantity()==reserve.getAmount()){
                    reserve.setState(Long.parseLong("0"));
                }
                int num2 = reserveDao.updateReserve(conn,Integer.parseInt(rid.toString()),reserve);
                if(num1==1&&num2==1){
                    flag = true;
                }else {
                    flag = false;
                }
            }
            if(!flag){
                conn.rollback();
            }
        }catch (Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            JDBCUtils.close(null,conn);
        }
        return flag;
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<ReceiveDetail> getAll() {
        return receiveDetailDao.selectAll();
    }
}
